<template>
  <el-dialog
    :title="isEditing ? '编辑数据模型' : '添加数据模型'"
    v-model="dialogVisible"
    width="60%"
    @closed="handleDialogClosed"
  >
    <el-form :model="form" label-width="100px" :rules="rules" ref="formRef">
      <el-form-item label="模型名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入模型名称" />
      </el-form-item>
      <el-form-item label="数据表名" prop="tableName">
        <el-input v-model="form.tableName" placeholder="请输入数据表名" />
      </el-form-item>
      <el-form-item label="模型分类" prop="catalog">
        <el-cascader
          v-model="form.catalog"
          :options="categoryOptions"
          :props="{ checkStrictly: true, value: 'id', label: 'name' }"
          clearable
          placeholder="请选择分类"
        />
      </el-form-item>
      <el-form-item label="模型描述">
        <el-input type="textarea" v-model="form.description" rows="3" placeholder="请输入模型描述" />
      </el-form-item>

      <el-divider>字段定义</el-divider>

      <div class="fields-container">
        <div class="fields-header">
          <el-button type="primary" size="small" @click="showAiGenerateDialog">
            <el-icon><Cpu /></el-icon> AI 生成字段
          </el-button>
          <el-button type="primary" size="small" @click="addField">
            <el-icon><Plus /></el-icon> 添加字段
          </el-button>
        </div>

        <el-table :data="form.fields" border style="width: 100%">
          <el-table-column label="字段名" prop="name" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.name" placeholder="字段名" />
            </template>
          </el-table-column>
          <el-table-column label="数据类型" prop="type" width="150">
            <template #default="scope">
              <el-select v-model="scope.row.type" placeholder="选择类型">
                <el-option label="字符串" value="string" />
                <el-option label="整数" value="integer" />
                <el-option label="浮点数" value="float" />
                <el-option label="布尔值" value="boolean" />
                <el-option label="日期" value="date" />
                <el-option label="时间戳" value="timestamp" />
                <el-option label="JSON" value="json" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="是否必填" prop="required" width="100">
            <template #default="scope">
              <el-switch v-model="scope.row.required" />
            </template>
          </el-table-column>
          <el-table-column label="默认值" prop="defaultValue">
            <template #default="scope">
              <el-input v-model="scope.row.defaultValue" placeholder="默认值" />
            </template>
          </el-table-column>
          <el-table-column label="描述" prop="description">
            <template #default="scope">
              <el-input v-model="scope.row.description" placeholder="字段描述" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <el-button type="danger" size="small" @click="removeField(scope.$index)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveModel">保存</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- AI 生成字段对话框 -->
  <el-dialog
    title="AI 生成数据表字段"
    v-model="showAiDialog"
    width="50%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="!isGenerating"
    class="ai-generate-dialog"
  >
    <div class="ai-dialog-content">
      <div class="ai-connection-status" :class="connectionStatusClass">
        <el-icon><Connection /></el-icon>
        <span>{{ connectionStatusText }}</span>
      </div>

      <el-form label-position="top">
        <el-form-item label="请描述您的数据表需求">
          <el-input
            v-model="aiPrompt"
            type="textarea"
            :rows="3"
            placeholder="例如：创建一个用户表，包含用户基本信息、联系方式和账户状态等字段"
            :disabled="isGenerating"
          />
        </el-form-item>
      </el-form>

      <!-- 历史记录下拉菜单 -->
      <div class="history-container" v-if="aiHistory.length > 0 && !isGenerating">
        <el-dropdown @command="handleHistoryCommand" trigger="click">
          <el-button type="info" plain size="small">
            <el-icon><Clock /></el-icon>
            历史记录 <el-icon><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-for="(item, index) in aiHistory"
                :key="index"
                :command="index"
              >
                <div class="history-item">
                  <div class="history-title">{{ item.title || '未命名' }}</div>
                  <div class="history-date">{{ formatDate(item.date) }}</div>
                </div>
              </el-dropdown-item>
              <el-dropdown-item divided command="clear">
                <el-icon><Delete /></el-icon> 清空历史记录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>

      <div v-if="isGenerating" class="generating-status">
        <el-progress :percentage="generatingProgress" :indeterminate="true" />
        <div class="generating-text">
          <span>AI 正在生成字段，请稍候...</span>
          <el-icon class="loading-icon"><Loading /></el-icon>
        </div>
      </div>

      <div v-if="aiResponse" class="ai-response">
        <h4>AI 生成结果：</h4>
        <div class="response-content" ref="responseContentRef" v-html="formattedAiResponse"></div>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showAiDialog = false" :disabled="isGenerating">取消</el-button>
        <el-button type="primary" @click="generateFields" :loading="isGenerating" :disabled="!aiPrompt || isGenerating || connectionStatus === 'error'">
          生成字段
        </el-button>
        <el-button type="success" @click="applyGeneratedFields" :disabled="!aiResponse || isGenerating">
          应用到表单
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 保存到历史记录对话框 -->
  <el-dialog
    title="保存到历史记录"
    v-model="showSaveHistoryDialog"
    width="30%"
  >
    <el-form>
      <el-form-item label="标题">
        <el-input v-model="historyTitle" placeholder="请输入标题，便于后续查找" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showSaveHistoryDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmSaveHistory">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, onUnmounted, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Cpu, Loading, Connection, Clock, ArrowDown, Star } from '@element-plus/icons-vue'
import http from '@/utils/request'
import config from '@/config/index'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  model: {
    type: Object,
    default: () => ({})
  },
  isEditing: {
    type: Boolean,
    default: false
  },
  categoryOptions: {
    type: Array,
    default: () => []
  },
  currentCategory: {
    type: Number,
    default: 0
  }
})

const emit = defineEmits(['update:visible', 'saved'])

// 对话框可见性
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

// 表单引用
const formRef = ref(null)

// 表单数据
const form = ref({
  id: null,
  name: '',
  tableName: '',
  catalog: null,
  description: '',
  fields: [
    { name: 'id', type: 'integer', required: true, defaultValue: '', description: '主键ID' }
  ]
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入模型名称', trigger: 'blur' },
  ],
  tableName: [
    { required: true, message: '请输入数据表名', trigger: 'blur' },
  ],
  catalog: [
    { required: true, message: '请选择模型分类', trigger: 'change' },
  ]
}

// AI 生成相关
const showAiDialog = ref(false)
const aiPrompt = ref('')
const aiResponse = ref('')
const aiThinking = ref('') // 存储思考过程
const aiResult = ref('') // 存储最终结果
const isGenerating = ref(false)
const generatingProgress = ref(0)
const websocket = ref(null)
const parsedFields = ref([])
const connectionStatus = ref('pending') // pending, connected, error
const canSaveToHistory = ref(true) // 控制是否可以保存到历史
const reconnectTimer = ref(null) // 重连定时器
const reconnectAttempts = ref(0) // 重连尝试次数
const MAX_RECONNECT_ATTEMPTS = 5 // 最大重连次数
const responseContentRef = ref(null) // 响应内容区域的引用

// 历史记录相关
const aiHistory = ref([])
const showSaveHistoryDialog = ref(false)
const historyTitle = ref('')
const HISTORY_STORAGE_KEY = 'ai_fields_generation_history'

// 连接状态文本
const connectionStatusText = computed(() => {
  switch (connectionStatus.value) {
    case 'pending':
      return '正在连接 AI 服务...'
    case 'connected':
      return 'AI 服务已连接'
    case 'error':
      return 'AI 服务连接失败'
    default:
      return '未知状态'
  }
})

// 连接状态样式类
const connectionStatusClass = computed(() => {
  return {
    'status-pending': connectionStatus.value === 'pending',
    'status-connected': connectionStatus.value === 'connected',
    'status-error': connectionStatus.value === 'error'
  }
})

// 格式化 AI 响应，将换行符转换为 <br>
const formattedAiResponse = computed(() => {
  // 如果有最终结果，优先显示结果，否则显示思考过程
  const content = aiResult.value || aiThinking.value || aiResponse.value
  return content.replace(/\n/g, '<br>')
})

// 格式化日期
const formatDate = (timestamp) => {
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 加载历史记录
const loadHistory = () => {
  try {
    const historyData = localStorage.getItem(HISTORY_STORAGE_KEY)
    if (historyData) {
      aiHistory.value = JSON.parse(historyData)
    }
  } catch (error) {
    console.error('加载历史记录失败:', error)
    aiHistory.value = []
  }
}

// 保存历史记录
const saveHistory = () => {
  try {
    localStorage.setItem(HISTORY_STORAGE_KEY, JSON.stringify(aiHistory.value))
  } catch (error) {
    console.error('保存历史记录失败:', error)
    ElMessage.error('保存历史记录失败')
  }
}

// 显示保存历史记录对话框
const saveToHistory = () => {
  if (!aiResponse.value) {
    ElMessage.warning('没有生成结果可保存')
    return
  }

  if (!canSaveToHistory.value) {
    ElMessage.warning('当前结果已保存到历史记录')
    return
  }

  historyTitle.value = form.value.name || form.value.tableName || '未命名模型'
  showSaveHistoryDialog.value = true
}

// 确认保存到历史记录
const confirmSaveHistory = () => {
  const historyItem = {
    title: historyTitle.value || '未命名',
    prompt: aiPrompt.value,
    thinking: aiThinking.value,
    result: aiResult.value,
    response: aiResponse.value,
    fields: parsedFields.value.length > 0 ? parsedFields.value : [],
    date: Date.now()
  }

  // 检查是否已存在相同内容的历史记录
  const existingIndex = aiHistory.value.findIndex(item =>
    item.prompt === historyItem.prompt &&
    (item.result === historyItem.result || item.response === historyItem.response)
  )

  if (existingIndex !== -1) {
    // 如果已存在，更新该记录
    aiHistory.value[existingIndex] = historyItem
    ElMessage.success('已更新历史记录')
  } else {
    // 如果不存在，添加新记录
    aiHistory.value.unshift(historyItem) // 添加到历史记录开头

    // 限制历史记录数量，最多保存20条
    if (aiHistory.value.length > 20) {
      aiHistory.value = aiHistory.value.slice(0, 20)
    }

    ElMessage.success('已保存到历史记录')
  }

  saveHistory()
  showSaveHistoryDialog.value = false
  canSaveToHistory.value = false // 保存后禁用保存按钮
}

// 处理历史记录命令
const handleHistoryCommand = (command) => {
  if (command === 'clear') {
    ElMessageBox.confirm('确定要清空所有历史记录吗？此操作不可恢复。', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      aiHistory.value = []
      saveHistory()
      ElMessage.success('历史记录已清空')
    }).catch(() => {})
    return
  }

  // 加载选中的历史记录
  const historyItem = aiHistory.value[command]
  if (historyItem) {
    aiPrompt.value = historyItem.prompt || ''
    aiThinking.value = historyItem.thinking || ''
    aiResult.value = historyItem.result || ''
    aiResponse.value = historyItem.result || historyItem.thinking || historyItem.response || ''

    if (historyItem.fields && historyItem.fields.length > 0) {
      parsedFields.value = historyItem.fields
    }

    canSaveToHistory.value = false // 从历史记录加载的内容不能再次保存
    ElMessage.success('已加载历史记录')
    
    // 加载历史记录后滚动到底部
    scrollResponseToBottom()
  }
}

// 监听响应内容变化，自动滚动到底部
watch([aiResponse, aiThinking, aiResult], () => {
  scrollResponseToBottom()
}, { immediate: false })

// 滚动响应内容到底部
const scrollResponseToBottom = () => {
  nextTick(() => {
    if (responseContentRef.value) {
      responseContentRef.value.scrollTop = responseContentRef.value.scrollHeight
    }
  })
}

// 显示 AI 生成对话框
const showAiGenerateDialog = () => {
  showAiDialog.value = true
  
  // 构建更丰富的提示词，包含模型名称和描述
  let promptText = ''
  
  if (form.value.name) {
    promptText += `创建一个"${form.value.name}"数据表`
  } else {
    promptText += '创建一个数据表'
  }
  
  if (form.value.description) {
    promptText += `，描述如下：${form.value.description}`
  }
  
  if (form.value.tableName) {
    promptText += `\n表名：${form.value.tableName}`
  }
  
  aiPrompt.value = promptText
  aiResponse.value = ''
  aiThinking.value = ''
  aiResult.value = ''
  parsedFields.value = []
  canSaveToHistory.value = true // 重置保存状态
  
  // 连接 AI 服务
  connectToAiService()
}

// 连接 AI 服务
const connectToAiService = () => {
  // 如果已经有连接，先关闭
  if (websocket.value && websocket.value.readyState !== WebSocket.CLOSED) {
    websocket.value.close()
  }

  // 重置重连计数
  reconnectAttempts.value = 0

  // 更新连接状态
  connectionStatus.value = 'pending'

  // 创建 WebSocket 连接
  try {
    const wsUrl = `${config.API_URL}/websocket`
    websocket.value = new WebSocket(wsUrl)

    websocket.value.onopen = () => {
      console.log('WebSocket 连接已建立')
      connectionStatus.value = 'connected'
      // 清除重连定时器
      if (reconnectTimer.value) {
        clearTimeout(reconnectTimer.value)
        reconnectTimer.value = null
      }
    }

    websocket.value.onclose = (event) => {
      console.log('WebSocket 连接已关闭', event)

      if (isGenerating.value) {
        isGenerating.value = false
        ElMessage.info('AI 服务连接已关闭')

        // 连接关闭时，最后一次尝试解析字段
        tryParseFieldsFromContent(aiResult.value || aiThinking.value || aiResponse.value)
      }

      // 如果不是主动关闭，尝试重连
      if (showAiDialog.value && connectionStatus.value !== 'error' && reconnectAttempts.value < MAX_RECONNECT_ATTEMPTS) {
        scheduleReconnect()
      } else if (reconnectAttempts.value >= MAX_RECONNECT_ATTEMPTS) {
        connectionStatus.value = 'error'
        ElMessage.error('连接 AI 服务失败，请稍后重试')
      }
    }

    websocket.value.onerror = (error) => {
      console.error('WebSocket 错误:', error)
      connectionStatus.value = 'error'

      if (isGenerating.value) {
        isGenerating.value = false
        ElMessage.error('连接 AI 服务出错')
      }
    }

    websocket.value.onmessage = (event) => {
      try {
        // 尝试解析 JSON
        const data = JSON.parse(event.data)

        if (data.messageType === 'reasoning') {
          // 处理思考过程
          aiThinking.value += data.content || ''
          aiResponse.value = aiThinking.value // 更新显示的响应
          scrollResponseToBottom() // 滚动到底部
        } else if (data.messageType === 'answer' || data.messageType === 'content') {
          // 处理最终结果
          if (data.content || data.message) {
            aiResult.value += data.content || data.message || ''
            aiResponse.value = aiResult.value // 更新显示的响应
            
            // 尝试从结果中解析字段
            tryParseFieldsFromContent(aiResult.value)
            scrollResponseToBottom() // 滚动到底部
          }
        } else if (data.messageType === 'over') {
          isGenerating.value = false
          generatingProgress.value = 100
          ElMessage.success('AI 生成完成')
          
          // 最后一次尝试解析字段
          tryParseFieldsFromContent(aiResult.value || aiThinking.value || aiResponse.value)
          scrollResponseToBottom() // 滚动到底部
        } else if (data.type === 'error') {
          isGenerating.value = false
          ElMessage.error(data.message || 'AI 生成失败')
        }
      } catch (error) {
        // 如果不是 JSON 格式，可能是纯文本响应
        console.log('收到非 JSON 格式的消息:', event.data)
        
        // 将原始数据添加到响应中
        aiResponse.value += event.data
        
        // 尝试从完整响应中解析字段
        tryParseFieldsFromContent(aiResponse.value)
        scrollResponseToBottom() // 滚动到底部
      }
    }
  } catch (error) {
    console.error('创建 WebSocket 连接失败:', error)
    connectionStatus.value = 'error'
    ElMessage.error('连接 AI 服务失败')
  }
}

// 安排重连
const scheduleReconnect = () => {
  if (reconnectTimer.value) {
    clearTimeout(reconnectTimer.value)
  }

  reconnectAttempts.value++
  const delay = Math.min(5000 * reconnectAttempts.value, 30000) // 指数退避，最大30秒

  console.log(`安排重连 (尝试 ${reconnectAttempts.value}/${MAX_RECONNECT_ATTEMPTS})，${delay}ms 后重试`)

  reconnectTimer.value = setTimeout(() => {
    console.log(`正在尝试重连 (${reconnectAttempts.value}/${MAX_RECONNECT_ATTEMPTS})`)
    connectToAiService()
  }, delay)
}

// 生成字段
const generateFields = () => {
  if (!aiPrompt.value) {
    ElMessage.warning('请输入数据表需求描述')
    return
  }
  
  if (connectionStatus.value === 'error') {
    ElMessage.error('AI 服务连接失败，请稍后重试')
    return
  }
  
  if (connectionStatus.value !== 'connected') {
    ElMessage.warning('正在连接 AI 服务，请稍候再试')
    return
  }

  isGenerating.value = true
  aiThinking.value = '' // 清空思考过程
  aiResult.value = '' // 清空最终结果
  aiResponse.value = '' // 清空显示的响应
  parsedFields.value = []
  generatingProgress.value = 0
  canSaveToHistory.value = true // 新生成的内容可以保存

  // 构建提示词，包含更多上下文信息
  const modelName = form.value.name || '未命名模型'
  const tableName = form.value.tableName || '未命名表'
  
  // 发送提示词
  websocket.value.send(JSON.stringify({
    type: 'prompt',
    message: `请帮我设计一个数据表，需求如下：${aiPrompt.value}
    
    模型名称：${modelName}
    表名：${tableName}
    
    请以JSON格式返回字段定义，包含字段名、类型、是否必填、默认值和描述。
    支持的类型有：string, integer, float, boolean, date, timestamp, json。
    
    示例格式：
    [
      {
        "name": "字段名",
        "type": "字段类型",
        "required": true/false,
        "defaultValue": "默认值",
        "description": "字段描述"
      }
    ]
    
    注意：
    1. 请确保字段名符合数据库命名规范，使用小写字母和下划线
    2. 请为每个字段提供详细的描述
    3. 根据字段用途合理设置是否必填
    4. 如果是主键字段，请命名为"id"并设置为必填
    `
  }))
}

// 应用生成的字段
const applyGeneratedFields = () => {
  if (!aiResponse.value) {
    ElMessage.warning('没有生成的字段可应用')
    return
  }

  try {
    // 首先检查是否已经成功解析了字段
    if (parsedFields.value.length > 0) {
      // 保留 ID 字段
      const idField = form.value.fields.find(f => f.name === 'id')

      // 替换字段列表，但保留 ID 字段
      form.value.fields = [
        idField || { name: 'id', type: 'integer', required: true, defaultValue: '', description: '主键ID' },
        ...parsedFields.value
      ]

      showAiDialog.value = false
      ElMessage.success('已应用 AI 生成的字段')
      return
    }

    // 如果没有预解析的字段，尝试从响应中提取 JSON 格式的字段定义
    const content = aiResult.value || aiThinking.value
    tryParseFieldsFromContent(content)

    if (parsedFields.value.length > 0) {
      // 保留 ID 字段
      const idField = form.value.fields.find(f => f.name === 'id')

      // 替换字段列表，但保留 ID 字段
      form.value.fields = [
        idField || { name: 'id', type: 'integer', required: true, defaultValue: '', description: '主键ID' },
        ...parsedFields.value
      ]

      showAiDialog.value = false
      ElMessage.success('已应用 AI 生成的字段')
    } else {
      ElMessage.warning('无法解析字段定义，请检查生成结果或手动添加字段')
    }
  } catch (error) {
    console.error('应用生成字段出错:', error)
    ElMessage.error('应用生成字段失败，请检查生成结果格式或手动添加字段')
  }
}

// 尝试从内容中提取 JSON 字段定义
const tryParseFieldsFromContent = (content) => {
  if (!content) return

  try {
    // 首先尝试从内容中提取 JSON 数组
    const jsonMatches = content.match(/\[\s*\{[^]*?\}\s*\]/gs)

    if (jsonMatches && jsonMatches.length > 0) {
      // 取最后一个匹配结果，通常是最完整的
      const jsonStr = jsonMatches[jsonMatches.length - 1]

      try {
        const fieldsData = JSON.parse(jsonStr)

        if (Array.isArray(fieldsData) && fieldsData.length > 0) {
          // 验证字段格式
          const validFields = fieldsData.filter(field =>
            field && typeof field === 'object' && field.name && typeof field.name === 'string'
          )

          if (validFields.length > 0) {
            parsedFields.value = validFields.map(field => ({
              name: field.name,
              type: field.type || 'string',
              required: field.required || false,
              defaultValue: field.defaultValue || '',
              description: field.description || ''
            }))

            console.log('成功解析字段:', parsedFields.value)
          }
        }
      } catch (jsonError) {
        console.log('JSON 解析失败:', jsonError)
      }
    } else {
      // 如果没有找到 JSON 数组，尝试解析文本格式
      console.log('未找到 JSON 格式，尝试解析文本格式')

      // 尝试查找字段定义的文本模式
      const fieldPattern = /(\w+)\s*\((\w+)\)(?:\s*\((\w+)\))?\s*:\s*(.+?)(?=\n\w+\s*\(|\n\s*\n|$)/gs
      const matches = [...content.matchAll(fieldPattern)]

      if (matches.length > 0) {
        const textFields = matches.map(match => ({
          name: match[1],
          type: match[2] || 'string',
          required: match[3] === 'required',
          defaultValue: '',
          description: match[4] || ''
        }))

        if (textFields.length > 0) {
          parsedFields.value = textFields
          console.log('从文本格式解析字段:', parsedFields.value)
        }
      }
    }
  } catch (error) {
    console.log('尝试解析字段失败:', error)
  }
}

// 监听模型数据变化
watch(() => props.model, (newVal) => {
  if (newVal && Object.keys(newVal).length > 0) {
    // 编辑模式，填充表单数据
    if (props.isEditing) {
      // 将后端返回的items转换为前端使用的fields格式
      const fields = newVal.items ? newVal.items.map(item => ({
        name: item.code || item.columnName,
        type: item.type || 'string',
        required: item.required || false,
        defaultValue: item.defaultValue || '',
        description: item.description || ''
      })) : []

      form.value = {
        id: newVal.id,
        name: newVal.name,
        tableName: newVal.tableName,
        catalog: newVal.catalog,
        description: newVal.description || newVal.note,
        fields: fields.length > 0 ? fields : [
          { name: 'id', type: 'integer', required: true, defaultValue: '', description: '主键ID' }
        ]
      }
    } else {
      // 添加模式，初始化表单
      form.value = {
        id: null,
        name: '',
        tableName: '',
        catalog: props.currentCategory === 0 ? null : props.currentCategory,
        description: '',
        fields: [
          { name: 'id', type: 'integer', required: true, defaultValue: '', description: '主键ID' }
        ]
      }
    }
  }
}, { immediate: true, deep: true })

// 添加字段
const addField = () => {
  form.value.fields.push({
    name: '',
    type: 'string',
    required: false,
    defaultValue: '',
    description: ''
  })
}

// 删除字段
const removeField = (index) => {
  form.value.fields.splice(index, 1)
}

// 保存模型
const saveModel = async () => {
  if (!form.value.name || !form.value.tableName || !form.value.catalog) {
    ElMessage.warning('请填写必填项')
    return
  }

  // 验证字段
  if (form.value.fields.length === 0) {
    ElMessage.warning('请至少添加一个字段')
    return
  }

  for (const field of form.value.fields) {
    if (!field.name || !field.type) {
      ElMessage.warning('字段名称和类型不能为空')
      return
    }
  }

  // 如果catalog是数组（级联选择器返回的值），取最后一个元素
  let catalogId = form.value.catalog
  if (Array.isArray(catalogId)) {
    catalogId = catalogId[catalogId.length - 1]
  }

  try {
    // 将字段转换为items格式
    const items = form.value.fields.map(field => ({
      code: field.name,
      columnName: field.name,
      type: field.type,
      required: field.required,
      defaultValue: field.defaultValue,
      description: field.description
    }))

    const data = {
      name: form.value.name,
      tableName: form.value.tableName,
      catalog: catalogId,
      description: form.value.description,
      items: items,
      code: form.value.tableName, // 使用tableName作为code
      icon: '',
      note: form.value.description // 使用description作为note
    }

    let res
    if (props.isEditing) {
      data.id = form.value.id
      res = await http.post('/module/update', data)
    } else {
      res = await http.post('/module/create', data)
    }

    if (res.code === 200) {
      ElMessage.success(props.isEditing ? '模型更新成功' : '模型添加成功')
      dialogVisible.value = false
      emit('saved')
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    console.error('保存模型出错:', error)
    ElMessage.error('操作失败，请检查网络连接')
  }
}

// 对话框关闭时重置表单
const handleDialogClosed = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.value = {
    id: null,
    name: '',
    tableName: '',
    catalog: null,
    description: '',
    fields: [
      { name: 'id', type: 'integer', required: true, defaultValue: '', description: '主键ID' }
    ]
  }
}

// 组件挂载时加载历史记录
onMounted(() => {
  // 加载历史记录
  loadHistory()
})

// 监听对话框关闭
watch(showAiDialog, (newVal) => {
  if (!newVal) {
    // 对话框关闭时，如果不在生成中，关闭 WebSocket 连接
    if (!isGenerating.value && websocket.value) {
      websocket.value.close()
    }

    // 清除重连定时器
    if (reconnectTimer.value) {
      clearTimeout(reconnectTimer.value)
      reconnectTimer.value = null
    }
  }
})

// 监听组件销毁
onUnmounted(() => {
  console.log('组件卸载，关闭 WebSocket 连接')

  // 关闭 WebSocket 连接
  if (websocket.value) {
    try {
      websocket.value.close()
      websocket.value = null
    } catch (error) {
      console.error('关闭 WebSocket 连接出错:', error)
    }
  }

  // 清除重连定时器
  if (reconnectTimer.value) {
    clearTimeout(reconnectTimer.value)
    reconnectTimer.value = null
  }
})
</script>

<style scoped>
.fields-container {
  margin-top: 20px;
}

.fields-header {
  margin-bottom: 10px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

.ai-dialog-content {
  min-height: 200px;
}

.generating-status {
  margin: 20px 0;
}

.generating-text {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
  color: #409eff;
}

.loading-icon {
  margin-left: 8px;
  animation: rotating 2s linear infinite;
}

.ai-response {
  margin-top: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  background-color: #f8fafc;
}

.ai-response h4 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #303133;
}

.response-content {
  white-space: pre-wrap;
  font-family: monospace;
  font-size: 14px;
  line-height: 1.5;
  color: #606266;
  overflow-y: auto;
  max-height: 200px; /* 限制响应内容的最大高度 */
  flex-grow: 1;
  scroll-behavior: smooth; /* 添加平滑滚动效果 */
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.ai-connection-status {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  margin-bottom: 16px;
  border-radius: 4px;
  font-size: 14px;
}

.ai-connection-status .el-icon {
  margin-right: 8px;
}

.status-pending {
  background-color: #e6f7ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
}

.status-connected {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.status-error {
  background-color: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

.history-container {
  margin: 16px 0;
  display: flex;
  justify-content: flex-start;
}

.history-item {
  display: flex;
  flex-direction: column;
  max-width: 200px;
}

.history-title {
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.history-date {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

/* 限制 AI 生成对话框的高度 */
:deep(.ai-generate-dialog .el-dialog) {
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  margin: 0 auto !important;
  position: relative;
  top: 10vh;
}

:deep(.ai-generate-dialog .el-dialog__body) {
  overflow-y: auto;
  max-height: calc(80vh - 120px); /* 减去标题和底部按钮的高度 */
  padding: 20px;
}

.ai-dialog-content {
  min-height: 200px;
  display: flex;
  flex-direction: column;
}

.ai-response {
  margin-top: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  background-color: #f8fafc;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.response-content {
  white-space: pre-wrap;
  font-family: monospace;
  font-size: 14px;
  line-height: 1.5;
  color: #606266;
  overflow-y: auto;
  max-height: 200px; /* 限制响应内容的最大高度 */
  flex-grow: 1;
  scroll-behavior: smooth; /* 添加平滑滚动效果 */
}
</style>
